#!/bin/perl

# this program takes a .CSV file that contains DB race information and processes it
# slightly, massaging the format.  It will change all team names to upper case, 
# remove spaces at end and change race times to be in seconds

my $fileName;
if ($#ARGV >= 0)
{
   $fileName = $ARGV[0]; 
}
else
{
   $fileName = "D:\\dragon boat\\2009\\Regression\\regressionPickeringSaturday.csv";
}


my $outFile;
my $i = 0;

my $teamName = 0;
my $category = 0;
my $time = 0;
my $raceNo = 0;
my $distance = 0;
my $festival = 0;
my $year = 0;
my $raceName = "";
my $validLine = 0;

# Read file into memory
# -----------------------------------------------------------------------------
open(F, "<$fileName") || die("Could not open $fileName");
my @lines=<F>;
my $line;
close(F);


$outFile = "$fileName.out";
open(F, ">$outFile") || die("Could not open $outFile");

for ($i=1;$i<=$#lines; $i++)
{
   $validLine = 0;
   $line=$lines[$i];
   chomp($line);
     
   if ($line =~ m/(.*)\,(.*)\,(.*)\,(.*)\,(.*)\,(.*)\,(.*),(.*),(.*)/ )
   {
      $teamName = $1;
      $category = $2;
      $time = $3;
      $raceNo = $4;
      $distance = $5;
      $festival = $6;
      $year = $7;
      $lane = $8;
      $raceName = $9;
      $validLine = 1;
   }  
   elsif ($line =~ m/(.*)\,(.*)\,(.*)\,(.*)\,(.*)\,(.*)\,(.*),(.*)/ )
   {
      $teamName = $1;
      $category = $2;
      $time = $3;
      $raceNo = $4;
      $distance = $5;
      $festival = $6;
      $year = $7;
      $lane = $8;
      $raceName = "";
      $validLine = 1;
   }
    
   if ($validLine == 1)
   {   
      $time = &convertToSeconds($time);
      
      # change name to uppercase
      $teamName = uc($teamName);
      # strip white space from beginning and end of team name
      $teamName =~ s/^\s*(.*?)\s*$/$1/;
      
      $category =~ s/^\s*(.*?)\s*$/$1/;
      
      $festival =~ s/^\s*(.*?)\s*$/$1/;
      
      print F "$teamName,$category,$time,$raceNo,$distance,$festival,$year,$lane,$raceName\n";     
   }      
}
   
close(F);


sub convertToSeconds()
{
   my $timeString = shift;
   my $minutes = 0;
   my $seconds = 0;
   my $centiseconds = 0;
   if ($timeString =~ m/(\d{1,2}):(\d\d)[\.|:](\d\d)/ )
   {
      $minutes = $1;
      $seconds = $2;
      $centiseconds = $3; 
   }
   elsif ($timeString =~ m/(\d{1,2}):(\d\d)\.(\d)/ )
   {
      $minutes = $1;
      $seconds = $2;
      $centiseconds = $3 * 10; 
   }

   
   return (($minutes * 60) + $seconds + ($centiseconds/100));
}
